<template>
  <div class="doctor-container">
    <div class="doctor-header">
      <el-form :inline="true" :model="queryParams" class="demo-form-inline">
        <el-form-item label="医生姓名">
          <el-input
            v-model="queryParams.name"
            placeholder="请输入医生姓名"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="所属科室">
          <el-select
            v-model="queryParams.departmentId"
            placeholder="请选择科室"
            clearable
          >
            <el-option
              v-for="item in departmentOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
            <el-option label="在职" :value="true" />
            <el-option label="离职" :value="false" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">查询</el-button>
          <el-button @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
      <el-button type="primary" @click="showCreateDialog">新增医生</el-button>
    </div>

    <el-table v-loading="loading" :data="doctorList" border>
      <el-table-column type="index" label="序号" width="50" />
      <el-table-column prop="name" label="姓名" width="120" />
      <el-table-column prop="title" label="职称" width="120" />
      <el-table-column prop="departmentName" label="所属科室" width="120" />
      <el-table-column prop="specialty" label="专长" show-overflow-tooltip />
      <el-table-column prop="status" label="状态" width="80">
        <template #default="{ row }">
          <el-tag :type="row.status ? 'success' : 'danger'">
            {{ row.status ? '在职' : '离职' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="200" fixed="right">
        <template #default="{ row }">
          <el-button type="primary" link @click="showEditDialog(row)">编辑</el-button>
          <el-button type="primary" link @click="handleDelete(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      v-model:current-page="queryParams.page"
      v-model:page-size="queryParams.size"
      :page-sizes="[10, 20, 30, 50]"
      :total="total"
      layout="total, sizes, prev, pager, next, jumper"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />

    <!-- 添加/修改医生对话框 -->
    <el-dialog
      :title="dialog.title"
      v-model="dialog.visible"
      width="600px"
      @close="handleDialogClose"
    >
      <el-form
        ref="doctorFormRef"
        :model="doctorForm"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="姓名" prop="name">
          <el-input v-model="doctorForm.name" placeholder="请输入医生姓名" />
        </el-form-item>
        <el-form-item label="职称" prop="title">
          <el-input v-model="doctorForm.title" placeholder="请输入职称" />
        </el-form-item>
        <el-form-item label="所属科室" prop="departmentId">
          <el-select
            v-model="doctorForm.departmentId"
            placeholder="请选择科室"
            style="width: 100%"
          >
            <el-option
              v-for="item in departmentOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="专长" prop="specialty">
          <el-input
            v-model="doctorForm.specialty"
            type="textarea"
            placeholder="请输入专长"
          />
        </el-form-item>
        <el-form-item label="简介" prop="introduction">
          <el-input
            v-model="doctorForm.introduction"
            type="textarea"
            :rows="3"
            placeholder="请输入简介"
          />
        </el-form-item>
        <el-form-item label="照片" prop="photoUrl">
          <el-upload
            class="avatar-uploader"
            action="/api/file/upload"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img v-if="doctorForm.photoUrl" :src="doctorForm.photoUrl" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="doctorForm.status">
            <el-radio :label="true">在职</el-radio>
            <el-radio :label="false">离职</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="用户名" prop="username">
          <el-input v-model="doctorForm.username" placeholder="请输入用户名，用于医生账号登录" />
        </el-form-item>
        <el-form-item label="电子邮箱" prop="email">
          <el-input v-model="doctorForm.email" placeholder="请输入电子邮箱" />
        </el-form-item>
        <el-form-item label="电话号码" prop="phone">
          <el-input v-model="doctorForm.phone" placeholder="请输入电话号码" />
        </el-form-item>
        <el-form-item label="密码" prop="password" v-if="!doctorForm.id">
          <el-input v-model="doctorForm.password" type="password" placeholder="请输入密码" />
        </el-form-item>
        <el-form-item label="确认密码" prop="confirmPassword" v-if="!doctorForm.id">
          <el-input v-model="doctorForm.confirmPassword" type="password" placeholder="请再次输入密码" />
        </el-form-item>
        <el-form-item label="密码" prop="password" v-else>
          <el-input v-model="doctorForm.password" type="password" placeholder="留空表示不修改密码" />
        </el-form-item>
        <el-form-item label="确认密码" prop="confirmPassword" v-if="doctorForm.id && doctorForm.password">
          <el-input v-model="doctorForm.confirmPassword" type="password" placeholder="请再次输入密码" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialog.visible = false">取 消</el-button>
          <el-button type="primary" @click="handleSubmit">确 定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import axios from 'axios'
import {
  getDoctorList,
  createDoctor,
  updateDoctor,
  deleteDoctor,
  getDoctorById,
  getUserByUsername
} from '@/api/doctor'
import { getDepartmentList } from '@/api/department'
import { register } from '@/api/user'

const loading = ref(false)
const total = ref(0)
const doctorList = ref([])
const doctorFormRef = ref()
const departmentOptions = ref([])

const queryParams = reactive({
  page: 1,
  size: 10,
  name: '',
  departmentId: undefined,
  status: undefined
})

const dialog = reactive({
  visible: false,
  title: ''
})

const doctorForm = reactive({
  id: undefined,
  name: '',
  title: '',
  departmentId: undefined,
  specialty: '',
  introduction: '',
  photoUrl: '',
  status: true,
  username: '',
  email: '',
  phone: '',
  password: '',
  confirmPassword: '',
  rePassword: '',
  passwordConfirm: ''
})

const rules = {
  name: [{ required: true, message: '请输入医生姓名', trigger: 'blur' }],
  title: [{ required: true, message: '请输入职称', trigger: 'blur' }],
  departmentId: [{ required: true, message: '请选择所属科室', trigger: 'change' }],
  status: [{ required: true, message: '请选择状态', trigger: 'change' }],
  username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
  email: [
    { required: true, message: '请输入电子邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的电子邮箱格式', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入电话号码', trigger: 'blur' },
    { pattern: /^1[3456789]\d{9}$/, message: '请输入正确的手机号格式', trigger: 'blur' }
  ],
  password: [{ 
    required: function(rule, value, callback) {
      // 新增时必填，编辑时可选
      return !doctorForm.id
    }, 
    message: '请输入密码', 
    trigger: 'blur' 
  }],
  confirmPassword: [
    { 
      required: function(rule, value, callback) {
        // 新增时必填，编辑时仅当修改密码时必填
        return !doctorForm.id || (doctorForm.id && doctorForm.password);
      }, 
      message: '请再次输入密码', 
      trigger: 'blur' 
    },
    { 
      validator: (rule, value, callback) => {
        if (value !== doctorForm.password) {
          callback(new Error('两次输入的密码不一致'));
        } else {
          callback();
        }
      }, 
      trigger: 'blur' 
    }
  ]
}

// 获取科室列表
const fetchDepartmentOptions = async () => {
  try {
    const response = await getDepartmentList({ page: 0, size: 100 })
    console.log('科室数据响应:', response);
    
    // 根据不同的响应结构处理数据
    if (response && response.content) {
      // 标准分页结构
      departmentOptions.value = response.content;
    } else if (response && Array.isArray(response)) {
      // 直接返回数组
      departmentOptions.value = response;
    } else if (response && response.data) {
      // 嵌套结构
      if (response.data.content) {
        departmentOptions.value = response.data.content;
      } else if (Array.isArray(response.data)) {
        departmentOptions.value = response.data;
      } else {
        departmentOptions.value = [];
      }
    } else {
      departmentOptions.value = [];
    }
  } catch (error) {
    console.error('获取科室列表失败:', error)
    departmentOptions.value = [];
  }
}

// 查询医生列表
const getList = async () => {
  try {
    loading.value = true
    const response = await getDoctorList({
      ...queryParams,
      page: queryParams.page - 1 // 后端页码从0开始
    })
    console.log('医生数据响应:', response);
    
    // 根据不同的响应结构处理数据
    if (response && response.content) {
      // 标准分页结构
      doctorList.value = response.content;
      total.value = response.totalElements;
    } else if (response && Array.isArray(response)) {
      // 直接返回数组
      doctorList.value = response;
      total.value = response.length;
    } else if (response && response.data) {
      // 嵌套结构
      if (response.data.content) {
        doctorList.value = response.data.content;
        total.value = response.data.totalElements;
      } else if (Array.isArray(response.data)) {
        doctorList.value = response.data;
        total.value = response.data.length;
      } else {
        doctorList.value = [];
        total.value = 0;
      }
    } else {
      doctorList.value = [];
      total.value = 0;
    }
  } catch (error) {
    console.error('获取医生列表失败:', error)
    doctorList.value = [];
    total.value = 0;
  } finally {
    loading.value = false
  }
}

// 查询按钮操作
const handleQuery = () => {
  queryParams.page = 1
  getList()
}

// 重置按钮操作
const resetQuery = () => {
  queryParams.name = ''
  queryParams.departmentId = undefined
  queryParams.status = undefined
  handleQuery()
}

// 显示创建对话框
const showCreateDialog = () => {
  // 重置表单数据
  Object.keys(doctorForm).forEach(key => {
    // 重置所有字段为默认空值
    if (typeof doctorForm[key] === 'string') {
      doctorForm[key] = '';
    } else if (typeof doctorForm[key] === 'boolean') {
      doctorForm[key] = true;
    } else if (typeof doctorForm[key] === 'number') {
      doctorForm[key] = undefined;
    } else {
      doctorForm[key] = undefined;
    }
  });
  
  doctorForm.id = null;
  doctorForm.status = true;
  
  // 重置验证
  if (doctorFormRef.value) {
    doctorFormRef.value.clearValidate();
  }
  
  dialog.title = '添加医生';
  dialog.visible = true;
  
  // 显示提示信息
  ElMessage({
    message: '提示：请务必输入医生姓名，此字段将用于显示在医生列表中',
    type: 'info',
    duration: 5000
  });
};

// 显示编辑对话框
const showEditDialog = (row) => {
  // 复制数据到表单
  Object.keys(doctorForm).forEach(key => {
    if (key in row) {
      doctorForm[key] = row[key];
    }
  });

  // 特殊处理密码字段 - 编辑时不显示密码
  doctorForm.password = '';
  doctorForm.confirmPassword = '';
  
  // 重置验证
  if (doctorFormRef.value) {
    doctorFormRef.value.clearValidate();
  }
  
  dialog.title = '编辑医生';
  dialog.visible = true;
};

// 删除按钮操作
const handleDelete = (row) => {
  ElMessageBox.confirm('确认要删除该医生吗？', '警告', {
    type: 'warning'
  }).then(async () => {
    try {
      await deleteDoctor(row.id)
      ElMessage.success('删除成功')
      getList()
    } catch (error) {
      console.error('删除医生失败:', error)
    }
  })
}

// 监听密码变化，确保confirmPassword始终与password一致
watch(() => doctorForm.password, (newVal) => {
  // 始终保持确认密码与密码一致
  doctorForm.confirmPassword = newVal
  doctorForm.rePassword = newVal
  doctorForm.passwordConfirm = newVal
})

// 监听confirmPassword变化，同步到其他确认密码字段
watch(() => doctorForm.confirmPassword, (newVal) => {
  doctorForm.rePassword = newVal
  doctorForm.passwordConfirm = newVal
})

// 处理表单提交
const handleSubmit = () => {
  doctorFormRef.value.validate(async valid => {
    if (valid) {
      const submitData = { ...doctorForm }; // 克隆数据以避免修改原始引用
      loading.value = true;
      console.log('提交的表单数据:', submitData);
      
      try {
        // 首先尝试查询用户名是否已存在
        const username = submitData.username;
        if (!username) {
          ElMessage.error('用户名不能为空');
          loading.value = false;
          return;
        }
        
        let userId = null;
        
        try {
          // 尝试获取用户信息
          const userResponse = await getUserByUsername(username);
          if (userResponse && userResponse.data && userResponse.data.id) {
            userId = userResponse.data.id;
            console.log(`找到现有用户 ID: ${userId} 用于用户名: ${username}`);
            ElMessage.info(`找到已存在用户 "${username}"，将直接关联医生记录`);
          }
        } catch (userError) {
          console.log(`用户 "${username}" 不存在，将创建新用户`, userError);
        }
        
        if (userId) {
          // 如果找到用户ID，直接创建医生记录并关联
          const doctorData = {
            userId: userId,
            username: submitData.username, // 保留用户名以便API识别
            name: submitData.name || submitData.username,
            title: submitData.title,
            departmentId: submitData.departmentId,
            specialty: submitData.specialty || '',
            introduction: submitData.introduction || '',
            photoUrl: submitData.photoUrl || '',
            status: submitData.status === false ? false : true,
            // 这里添加密码字段，因为API可能仍要求这些字段
            password: '123456',
            confirmPassword: '123456'
          };
          
          console.log('关联已存在用户创建医生:', doctorData);
          const response = await createDoctor(doctorData);
          ElMessage.success('成功创建医生并关联到现有用户');
          console.log('创建成功响应:', response);
          dialog.visible = false;
          getList();
        } else {
          // 如果没有找到用户ID，创建新用户并关联医生
          // 确保密码字段存在
          if (!submitData.password) {
            submitData.password = '123456';
            submitData.confirmPassword = '123456';
          }
          
          // 注册新用户
          const userRegisterData = {
            username: submitData.username,
            password: submitData.password,
            confirmPassword: submitData.confirmPassword,
            email: submitData.email || `${submitData.username}@example.com`,
            phone: submitData.phone || '13800000000'
          };
          
          console.log('准备注册新用户:', userRegisterData);
          const registerResponse = await register(userRegisterData);
          
          if (registerResponse && registerResponse.data) {
            // 获取新用户ID
            const newUserId = registerResponse.data.id;
            console.log('用户注册成功，用户ID:', newUserId);
            
            // 创建医生记录
            const newDoctorData = {
              userId: newUserId,
              username: submitData.username,
              name: submitData.name || submitData.username,
              title: submitData.title,
              departmentId: submitData.departmentId,
              specialty: submitData.specialty || '',
              introduction: submitData.introduction || '',
              photoUrl: submitData.photoUrl || '',
              status: submitData.status === false ? false : true
            };
            
            console.log('准备创建医生记录:', newDoctorData);
            const doctorResponse = await createDoctor(newDoctorData);
            ElMessage.success('成功创建用户和医生记录');
            console.log('创建医生成功响应:', doctorResponse);
            dialog.visible = false;
            getList();
          }
        }
      } catch (error) {
        console.error('创建医生过程中发生错误:', error);
        
        // 尝试最后的备用方法
        try {
          // 如果有响应信息，显示更详细的错误
          const errorMsg = error.response && error.response.data ? 
            error.response.data.message : error.message;
          
          console.log('尝试最终备用方法 - 直接通过Axios调用API');
          const token = localStorage.getItem('token');
          
          // 创建包含所有必要信息的数据对象
          const completeData = {
            username: submitData.username,
            password: submitData.password || '123456',
            confirmPassword: submitData.confirmPassword || '123456',
            name: submitData.name,
            title: submitData.title,
            departmentId: submitData.departmentId,
            specialty: submitData.specialty || '',
            introduction: submitData.introduction || '',
            photoUrl: submitData.photoUrl || '',
            status: submitData.status === false ? false : true,
            email: submitData.email || `${submitData.username}@example.com`,
            phone: submitData.phone || '13800000000'
          };
          
          console.log('备用方法 - 发送完整数据:', completeData);
          
          const directResponse = await axios({
            url: 'http://localhost:8080/api/doctor',
            method: 'post',
            headers: {
              'Content-Type': 'application/json',
              'Authorization': token ? (token.startsWith('Bearer ') ? token : `Bearer ${token}`) : ''
            },
            data: completeData
          });
          
          if (directResponse.status === 200 || directResponse.status === 201) {
            ElMessage.success('使用备用方法成功创建医生');
            console.log('备用方法成功:', directResponse);
            dialog.visible = false;
            getList();
          }
        } catch (finalError) {
          console.error('所有创建医生的尝试均失败:', finalError);
          ElMessage.error(`创建医生失败: ${finalError.message || '未知错误'}`);
        }
      } finally {
        loading.value = false;
      }
        
      // 更新医生记录
      if (submitData.id) {
        try {
          const response = await updateDoctor(submitData.id, submitData);
          ElMessage.success('医生信息更新成功');
          dialog.visible = false;
          getList();
        } catch (error) {
          console.error('更新医生失败:', error);
          ElMessage.error(`更新医生失败: ${error.message || '未知错误'}`);
          loading.value = false;
        }
      }
    } else {
      console.log('表单验证失败');
      return false;
    }
  });
};

// 对话框关闭时重置表单
const handleDialogClose = () => {
  if (doctorFormRef.value) {
    doctorFormRef.value.resetFields()
  }
}

// 分页大小改变
const handleSizeChange = (val) => {
  queryParams.size = val
  getList()
}

// 页码改变
const handleCurrentChange = (val) => {
  queryParams.page = val
  getList()
}

// 上传头像之前的钩子
const beforeAvatarUpload = (file) => {
  const isJPG = file.type === 'image/jpeg'
  const isPNG = file.type === 'image/png'
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isJPG && !isPNG) {
    ElMessage.error('上传头像图片只能是 JPG/PNG 格式!')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('上传头像图片大小不能超过 2MB!')
    return false
  }
  return true
}

// 头像上传成功的回调
const handleAvatarSuccess = (response) => {
  doctorForm.photoUrl = response.data
}

onMounted(() => {
  fetchDepartmentOptions()
  getList()
})
</script>

<style lang="scss" scoped>
.doctor-container {
  padding: 20px;

  .doctor-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
  }

  :deep(.el-pagination) {
    margin-top: 20px;
    justify-content: flex-end;
  }
}

.avatar-uploader {
  :deep(.el-upload) {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);

    &:hover {
      border-color: var(--el-color-primary);
    }
  }
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  text-align: center;
  line-height: 100px;
}

.avatar {
  width: 100px;
  height: 100px;
  display: block;
  object-fit: cover;
}
</style> 